from audio_pkg.models.taskdata import TaskSuccessDate, TaskFailureDate, TaskRunningDate
from audio_pkg.core.handler.base_handler import BaseStatusHandler
from typing import Dict, Any, List,Optional
from datetime import datetime
import requests
import json
import os


class TaskSuccessHandler(BaseStatusHandler):
    def __init__(self,  mime_config:dict):
        self.mime_config = mime_config
    
    def handle(self, task_info: dict) -> Optional[TaskSuccessDate]:
        task_url = task_info.get("task_result").get("speech_url")
        self.audio_resource = requests.get(url=task_url)

        # 检查是否过期
        if self.verify_expire(task_info.get("task_id")):
            return None  # 或者返回 False，取决于你的需求

        # 如果没有过期，返回音频数据
        task_bytes = self.audio_resource.content
        return TaskSuccessDate(
            speech_url=task_url,
            audio_data=task_bytes,
            task_id=task_info.get("task_id"),
            audio_type=self._parse()
        )
    
    def _parse(self):
        # 获取音频格式，并根据 MIME 类型返回相应的扩展名

        return self.mime_config.get(self.content_type, "unknow")
    
    def verify_expire(self,task_id) -> bool:
        """
        验证任务是否过期，过期则返回 True，未过期则返回 False
        """
        self.content_type = self.audio_resource.headers.get("Content-Type", "")
        
        # 如果返回的是 JSON 格式的响应
        if "application/json" in self.content_type:
            try:
                # 尝试解析 JSON 数据
                json_v = self.audio_resource.json()
                # 如果返回的 JSON 中有 "RequestExpired" 错误代码，则表示任务过期
                if json_v.get("code") == "RequestExpired":
                    print(f"任务-{task_id}-过期: {json_v.get('message')}")
                    return True  # 表示任务过期
            except requests.exceptions.JSONDecodeError:
                print("解析错误: 返回的不是有效的 JSON 格式")

        return False
        



class TaskRunningHandler(BaseStatusHandler):
    def handle(self, task_info: dict):
        return TaskRunningDate(
            task_id=task_info.get("task_id"),
        )
    

class TaskFailureHandler(BaseStatusHandler):
    def handle(self, task_info: dict):
        return TaskFailureDate(
            task_id=task_info.get("task_id")
        )
    


class TaskParseHandler:

    def __init__(self,handlers:Dict[str, BaseStatusHandler]):
        self.handlers = handlers
        self._task_results:List[TaskSuccessDate] = []
        
    def handle(self, task_info: List[Dict[str, Any]]):
        for task in task_info:
            task_status = task.get("task_status")
            handler = self.handlers.get(task_status)
            if handler: 
                result = handler.handle(task)  # 调用处理器的 handle 方法
                if result:
                    self._task_results.append(result)

    def result(self) -> list:
        return self._task_results


class TaskFileHandler:
    def __init__(self, logger, filename:str):
        self.filename = filename
        self.logger = logger

    def handle(self, response_json: Dict[str, Any], response_format: str) -> None:
        """处理并保存任务响应数据"""
        try:
            # 1. 添加额外字段
            enriched_data = self._enrich_response(response_json, response_format)
            
            # 2. 读取现有数据
            existing_data = self._read_existing_data()
            
            # 3. 追加新数据
            updated_data = self._append_data(existing_data, enriched_data)
            
            # 4. 写入文件
            self._write_data(updated_data)
            
            self.logger.info(f"任务数据已追加到文件 {self.filename}")
        except Exception as e:
            self.logger.error(f"处理任务数据失败：{str(e)}")
            raise

    def _enrich_response(self, data: Dict[str, Any], fmt: str) -> Dict[str, Any]:
        """添加时间戳和音频格式字段"""
        return {
            **data,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),  
            "format": fmt
        }

    def _read_existing_data(self) -> list:
        """读取现有 JSON 数据"""
        if not os.path.exists(self.filename):
            return []

        try:
            with open(self.filename, "r", encoding="utf-8") as f:
                data = json.load(f)
                return data if isinstance(data, list) else []
        except json.JSONDecodeError:
            self.logger.warning("检测到损坏的 JSON 文件，将重置数据")
            return []

    def _append_data(self, existing: list, new_data: Dict[str, Any]) -> list:
        """追加新数据到现有数据集"""
        return [*existing, new_data]

    def _write_data(self, data: list) -> None:
        """将数据写入文件"""
        with open(self.filename, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def load_all_tasks(self) -> list:
        """加载全部历史任务数据（可选方法）"""
        return self._read_existing_data()



